package com.hnhegui.backend.system.service;

import com.hnhegui.backend.exception.BusinessException;
import com.hnhegui.backend.system.dto.request.LoginRequestDTO;
import com.hnhegui.backend.system.dto.response.LoginResponseDTO;
import com.hnhegui.backend.system.entity.User;
import com.hnhegui.backend.system.mapper.UserMapper;
import com.hnhegui.backend.util.JwtUtil;
import com.hnhegui.backend.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class AuthService {


    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private RedisUtil redisUtil;

    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    /**
     * 用户登录
     */
    public LoginResponseDTO login(LoginRequestDTO request) {
        // 根据登录类型查询用户
        User user = findUserByLoginType(request.getUsername(), request.getLoginType());

        if (user == null) {
            throw new BusinessException(40101, "用户不存在");
        }

        // 验证用户状态
        if (user.getStatus() == 0) {
            throw new BusinessException(40102, "用户已被禁用");
        }

        // 验证密码
        if (!passwordEncoder.matches(request.getPassword(), user.getPassword())) {
            throw new BusinessException(40103, "密码错误");
        }

        // 生成Token
        String token = jwtUtil.generateToken(user.getUserId(), user.getUsername(), user.getRole().name());

        // 存储Token到Redis
        String redisKey = "auth:token:" + user.getUserId();
        redisUtil.set(redisKey, token, jwtUtil.getExpirationSeconds(), TimeUnit.SECONDS);

        // 构建响应
        LoginResponseDTO response = new LoginResponseDTO();
        response.setToken(token);
        response.setTokenType("Bearer");
        response.setExpiresIn(jwtUtil.getExpirationSeconds());
        response.setUserId(user.getUserId().toString());
        response.setUsername(user.getUsername());
        response.setRole(user.getRole().name());

        return response;
    }

    /**
     * 根据登录类型查找用户
     */
    private User findUserByLoginType(String username, String loginType) {
        if ("PHONE".equals(loginType)) {
            return userMapper.findByPhone(username);
        } else if ("EMAIL".equals(loginType)) {
            return userMapper.findByEmail(username);
        } else {
            return userMapper.findByUsername(username);
        }
    }

    /**
     * 验证Token
     */
    public boolean validateToken(String token, Long userId) {
        // 验证JWT Token格式和有效期
        if (!jwtUtil.validateToken(token)) {
            return false;
        }

        // 验证Redis中是否存在
        String redisKey = "auth:token:" + userId;
        Object storedToken = redisUtil.get(redisKey);

        return storedToken != null && token.equals(storedToken.toString());
    }

    /**
     * 登出
     */
    public void logout(Long userId) {
        String redisKey = "auth:token:" + userId;
        redisUtil.delete(redisKey);
    }
}
